//
//  UIImage+ABCDynamicWeb.m
//  ABCAppearanceKit_Example
//
//  Created by mac on 2022/9/8.
//  Copyright © 2022 Joe. All rights reserved.
//

#import "UIImage+ABCDynamicWeb.h"
#import "UIImage+ABCDynamic.h"
#import "SDWebImageManager.h"

@implementation UIImage (ABCDynamicWeb)

+ (void)abc_dynamicWithLightImageUrl:(NSURL *)lightImageUrl
                        darkImageUrl:(NSURL *)darkImageUrl
                          completion:(nonnull void (^)(UIImage * _Nullable, NSError * _Nullable))completion {
    if (@available(iOS 13.0, *)) {
        __block UIImage *lightImage = nil, *darkImage = nil;
        __block NSError *loadError = nil;
        dispatch_block_t requestImageComplateBlock = ^(){
            if (lightImage || darkImage) {
                if (completion) {
                    completion([UIImage abc_dynamicWithLightImage:lightImage darkImage:darkImage], nil);
                }
            } else {
                if (!loadError) {
                    loadError = [NSError errorWithDomain:@"ABCDynamicImageDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"request web image failed"}];
                }
                if (completion) {
                    completion(nil,loadError);
                }
            }
        };
        
        [[SDWebImageManager sharedManager]loadImageWithURL:lightImageUrl options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (finished) {
                lightImage = image;
            }
            if (!loadError && error) {
                loadError = error;
            }
            requestImageComplateBlock();
        }];
        
        [[SDWebImageManager sharedManager]loadImageWithURL:darkImageUrl options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (finished) {
                darkImage = image;
            }
            if (!loadError && error) {
                loadError = error;
            }
            requestImageComplateBlock();
        }];
    } else {
        [[SDWebImageManager sharedManager]loadImageWithURL:lightImageUrl options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (completion) {
                completion(image, error);
            }
        }];
    }
}

@end
